from flask import Flask
from flask_sqlalchemy import SQLAlchemy

from flask_session import Session
from config import config, Config
import logging
from logging.handlers import RotatingFileHandler
from redis import StrictRedis
from flask_wtf import CSRFProtect,csrf
logging.basicConfig(level=logging.DEBUG)
file_log_hander = RotatingFileHandler("logs/log", maxBytes=10*10*100, backupCount=10)
formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
file_log_hander.setFormatter(formatter)
logging.getLogger().addHandler(file_log_hander)


db = SQLAlchemy()

redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT,decode_responses=True)


def create_app(config_name):
    from info.modules.index import index_blue
    from info.modules.password import passport_blue
    from info.modules.profile import profile_blue
    from info.modules.admin import admin_blue
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    Session(app)
    app.register_blueprint(index_blue)
    app.register_blueprint(passport_blue)
    app.register_blueprint(profile_blue)
    app.register_blueprint(admin_blue)
    CSRFProtect(app)
    @app.after_request
    def after_request(response):
        csrf_token = csrf.generate_csrf()
        response.set_cookie("csrf_token",csrf_token)
        return response


    # @app.after_request
    # def after_request(response):
    #     csrf_token = csrf.generate_csrf()
    #     # 写入到客户端浏览器的cookie中
    #     response.set_cookie('csrf_token',csrf_token)
    #     return response
    from info.utils.commons import index_filter,status_filter
    app.add_template_filter(index_filter,"index_filter")
    app.add_template_filter(status_filter,"status_filter")

    return app


